package com.supermap.desktop.CtrlAction.Dataset;

import java.text.MessageFormat;
import java.util.List;
import java.util.Vector;
import java.util.concurrent.CancellationException;

import com.supermap.data.Dataset;
import com.supermap.data.Datasource;
import com.supermap.data.SteppedEvent;
import com.supermap.data.SteppedListener;
import com.supermap.data.Workspace;
import com.supermap.desktop.Application;
import com.supermap.desktop.CommonToolkit;
import com.supermap.desktop.dataeditor.DataEditorProperties;
import com.supermap.desktop.progress.Interface.UpdateProgressCallable;
import com.supermap.desktop.properties.CommonProperties;
import com.supermap.desktop.ui.UICommonToolkit;
import com.supermap.desktop.ui.controls.mutiTable.component.MutiTable;
import com.supermap.desktop.ui.controls.mutiTable.component.MutiTableModel;

public class DatasetCopyCallable extends UpdateProgressCallable {
	private static final int COLUMN_INDEX_Dataset = 0;
	private static final int COLUMN_INDEX_CurrentDatasource = 1;
	private static final int COLUMN_INDEX_TargetDatasource = 2;
	private static final int COLUMN_INDEX_TargetDataset = 3;
	private static final int COLUMN_INDEX_EncodeType = 4;
	private static final int COLUMN_INDEX_Charset = 5;
	private MutiTable table;

	DatasetCopyCallable(MutiTable table) {
		this.table = table;
	}

	@Override
	public Boolean call() throws Exception {
		try {
			MutiTableModel tableModel = (MutiTableModel) table.getModel();

			final int count = table.getRowCount();
			List<Object> contents = tableModel.getContents();
			Workspace workspace = Application.getActiveApplication().getWorkspace();

			for (int i = 0; i < count; i++) {
				@SuppressWarnings("unchecked")
				Vector<Object> vector = (Vector<Object>) contents.get(i);
				String currentDatasourceStr = vector.get(COLUMN_INDEX_CurrentDatasource).toString();
				String datasetStr = vector.get(COLUMN_INDEX_Dataset).toString();
				String targetDatasourceStr = vector.get(COLUMN_INDEX_TargetDatasource).toString();
				String targetDatasetName = vector.get(COLUMN_INDEX_TargetDataset).toString();
				String encodingType = vector.get(COLUMN_INDEX_EncodeType).toString();
				String charset = vector.get(COLUMN_INDEX_Charset).toString();
				Datasource currentDatasource = workspace.getDatasources().get(currentDatasourceStr);
				Dataset dataSet = currentDatasource.getDatasets().get(datasetStr);
				Datasource targetDatasource = workspace.getDatasources().get(targetDatasourceStr);
				Dataset resultDataset = null;
				if ("".equals(targetDatasetName) || targetDatasetName.isEmpty() || !isAviliableName(targetDatasetName)
						|| !targetDatasource.getDatasets().isAvailableDatasetName(targetDatasetName)) {
					targetDatasetName = targetDatasource.getDatasets().getAvailableDatasetName(targetDatasetName);
				}
				if (!targetDatasource.isReadOnly()) {
					targetDatasource.addSteppedListener(new PercentListener(i, count));
					resultDataset = targetDatasource.copyDataset(dataSet, targetDatasetName, CommonToolkit.EncodeTypeWrap.findType(encodingType),
							CommonToolkit.CharsetWrap.getCharset(charset));
				} else {
					String info = String.format(DataEditorProperties.getString("String_PluginDataEditor_MessageCopyDatasetOne"), targetDatasourceStr);
					Application.getActiveApplication().getOutput().output(info);
				}
				if (null != resultDataset) {

					String copySuccess = String.format(DataEditorProperties.getString("String_CopyDataset_Success2"), currentDatasourceStr, datasetStr,
							targetDatasourceStr, targetDatasetName);
					Application.getActiveApplication().getOutput().output(copySuccess);
					// 刷新数据集对应的数据源节点并选中数据集
					UICommonToolkit.refreshSelectedDatasetNode(resultDataset);
				} else {
					String copyFailed = String.format(DataEditorProperties.getString("String_CopyDataset_Failed"), currentDatasourceStr, datasetStr,
							targetDatasourceStr);
					Application.getActiveApplication().getOutput().output(copyFailed);
				}
			}
		} catch (Exception ex) {
			Application.getActiveApplication().getOutput().output(ex);
		}
		return true;
	}

	private boolean isAviliableName(String datasetName) {
		boolean flag = false;
		char c = datasetName.charAt(0);
		if ('_' == c || ('0' < c && c < '9')) {
			flag = false;
		} else {
			flag = true;
		}
		return flag;
	}

	class PercentListener implements SteppedListener {
		private int count;
		private int i;

		PercentListener(int i, int count) {
			this.count = count;
			this.i = i;
		}

		@Override
		public void stepped(SteppedEvent arg0) {
			try {
				int totalPercent = (int) ((i + (0.0) / this.count) * 100);
				updateProgressTotal(arg0.getPercent(), totalPercent, arg0.getMessage(),
						MessageFormat.format(CommonProperties.getString("String_Message_SubProgress"), arg0.getPercent()));
			} catch (CancellationException e) {
				arg0.setCancel(true);
			}

		}

	}
}
